package com.example.myapplication.adapter

import android.graphics.Color
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.example.myapplication.databinding.ItemTradingPointBinding
import com.example.myapplication.model.PointType
import com.example.myapplication.model.TradingPoint
import com.example.myapplication.utils.TradingTimeHelper
import android.view.View

/**
 * 买卖点列表适配器
 */
class TradingPointAdapter : ListAdapter<TradingPoint, TradingPointAdapter.ViewHolder>(DiffCallback()) {
    
    // 存储买卖配对信息，用于计算盈亏
    private val tradingPairs = mutableListOf<TradingPair>()
    
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val binding = ItemTradingPointBinding.inflate(
            LayoutInflater.from(parent.context),
            parent,
            false
        )
        return ViewHolder(binding)
    }
    
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bind(getItem(position), position)
    }
    
    override fun submitList(list: List<TradingPoint>?) {
        super.submitList(list)
        // 计算买卖配对
        list?.let { calculateTradingPairs(it) }
    }
    
    /**
     * 计算买卖配对，用于显示盈亏
     */
    private fun calculateTradingPairs(points: List<TradingPoint>) {
        tradingPairs.clear()
        
        var buyPoint: TradingPoint? = null
        
        for (point in points) {
            when (point.type) {
                PointType.BUY -> {
                    // 记录买入点
                    buyPoint = point
                }
                PointType.SELL -> {
                    // 找到对应的买入点，计算收益
                    buyPoint?.let { buy ->
                        val profitRate = (point.price - buy.price) / buy.price * 100
                        tradingPairs.add(TradingPair(buy, point, profitRate))
                        buyPoint = null // 清空，准备下一对
                    }
                }
            }
        }
    }
    
    /**
     * 获取某个卖出点对应的收益率
     */
    private fun getProfitForSellPoint(sellPoint: TradingPoint): Double? {
        return tradingPairs.find { it.sellPoint == sellPoint }?.profitRate
    }
    
    inner class ViewHolder(
        private val binding: ItemTradingPointBinding
    ) : RecyclerView.ViewHolder(binding.root) {
        
        fun bind(point: TradingPoint, position: Int) {
            // 设置类型和索引
            val isBuy = point.type == PointType.BUY
            val isCurrentRecommendation = point.reason?.startsWith("⭐ 当前推荐") ?: false  // 判断是否为当前推荐
            
            val typeIndex = if (isBuy) {
                currentList.take(position + 1).count { it.type == PointType.BUY }
            } else {
                currentList.take(position + 1).count { it.type == PointType.SELL }
            }
            
            binding.pointTypeTextView.apply {
                text = if (isCurrentRecommendation) {
                    if (isBuy) "⭐ 推荐买入" else "⭐ 推荐卖出"
                } else {
                    if (isBuy) "买入" else "卖出"
                }
                setBackgroundColor(if (isBuy) Color.parseColor("#00C853") else Color.parseColor("#FF1744"))
            }
            
            binding.pointIndexTextView.text = if (isCurrentRecommendation) "最新" else "#$typeIndex"
            
            // 设置日期
            binding.pointDateTextView.text = TradingTimeHelper.formatDate(point.timestamp)
            
            // 设置价格
            binding.pointPriceTextView.text = "¥%.2f".format(point.price)
            binding.pointPriceTextView.setTextColor(
                if (isBuy) Color.parseColor("#00C853") else Color.parseColor("#FF1744")
            )
            
            // 设置原因（如果是当前推荐，去掉前缀）
            binding.pointReasonTextView.text = if (isCurrentRecommendation) {
                point.reason?.replace("⭐ 当前推荐：", "") ?: "当前推荐"
            } else {
                point.reason ?: "暂无原因"
            }
            
            // 设置信号强度
            binding.pointStrengthTextView.text = "${point.strength}/100"
            binding.pointStrengthTextView.setTextColor(
                when {
                    point.strength >= 70 -> Color.parseColor("#4CAF50")
                    point.strength >= 50 -> Color.parseColor("#FF9800")
                    else -> Color.parseColor("#F44336")
                }
            )
            
            // 如果是卖出点，显示盈亏
            if (!isBuy) {
                val profit = getProfitForSellPoint(point)
                if (profit != null) {
                    binding.profitTextView.visibility = View.VISIBLE
                    binding.profitTextView.text = if (profit >= 0) {
                        "+%.1f%%".format(profit)
                    } else {
                        "%.1f%%".format(profit)
                    }
                    binding.profitTextView.setTextColor(
                        if (profit >= 0) Color.parseColor("#00C853") else Color.parseColor("#FF1744")
                    )
                } else {
                    binding.profitTextView.visibility = View.GONE
                }
            } else {
                binding.profitTextView.visibility = View.GONE
            }
        }
    }
    
    private class DiffCallback : DiffUtil.ItemCallback<TradingPoint>() {
        override fun areItemsTheSame(oldItem: TradingPoint, newItem: TradingPoint): Boolean {
            return oldItem.timestamp == newItem.timestamp && oldItem.type == newItem.type
        }
        
        override fun areContentsTheSame(oldItem: TradingPoint, newItem: TradingPoint): Boolean {
            return oldItem == newItem
        }
    }
    
    /**
     * 买卖配对数据类
     */
    private data class TradingPair(
        val buyPoint: TradingPoint,
        val sellPoint: TradingPoint,
        val profitRate: Double  // 盈利率（百分比）
    )
}

